/**
  logger.c - Created by Timothy Morey on 5/21/2012
*/

#include <stdio.h>
#include <string.h>

#include "logger.h"

#ifdef __WINDOWS__
#pragma warning(disable:4996)
#endif


/*****************************************************************************
 * Local definitions
 *****************************************************************************/

FILE* g_LogFile = 0;
LogLevel g_FileLogLevel;
LogLevel g_StdoutLogLevel;
LogLevel g_StderrLogLevel;


/*****************************************************************************
 * Implementation of logger.h functions
 *****************************************************************************/

int ChangeLogLevels(LogLevel fileLevel, LogLevel stdoutLevel, LogLevel stderrLevel)
{
	int retval = 0;
	char logmsg[256];

  g_FileLogLevel = fileLevel;
  g_StdoutLogLevel = stdoutLevel;
  g_StderrLogLevel = stderrLevel;
	sprintf(logmsg, "Log levels changed: file=%d, stdout=%d, stderr=%d", 
					g_FileLogLevel, g_StdoutLogLevel, g_StderrLogLevel);
	WriteMessage(LogLevelInfo, logmsg);
	retval = 1;

	return retval;
}

int InitLogger(const char* filename,
               LogLevel fileLevel, LogLevel stdoutLevel, LogLevel stderrLevel)
{
  int retval = 0;

  g_FileLogLevel = fileLevel;
  g_StdoutLogLevel = stdoutLevel;
  g_StderrLogLevel = stderrLevel;

  g_LogFile = fopen(filename, "a");
  if(g_LogFile)
  {
    fprintf(g_LogFile, "\n");
    fprintf(g_LogFile, "--------------------------\n");
    fprintf(g_LogFile, "| Started Logger Session |\n");
    fprintf(g_LogFile, "--------------------------\n");
		fflush(g_LogFile);

		retval = ChangeLogLevels(fileLevel, stdoutLevel, stderrLevel);
  }
  else
  {
    fprintf(stderr, "Failed to initialize logger\n");
  }

  return retval;
}

int WriteMessage(LogLevel level, const char* msg)
{
  int retval = 0;

  if(level > LogLevelMute)
  {
    char levelStr[8];
    char fmsg[4096];

    if(LogLevelInfo == level)
      strcpy(levelStr, "Info");
    else if(LogLevelDebug == level)
      strcpy(levelStr, "Debug");
    else if(LogLevelError == level)
      strcpy(levelStr, "ERROR");
    else
      strcpy(levelStr, "???");

    sprintf(fmsg, "%s: %s\n", levelStr, msg);

    if((level & g_FileLogLevel) && g_LogFile)
    {
      fprintf(g_LogFile, fmsg);
      fflush(g_LogFile);
    }

    if(level & g_StdoutLogLevel)
      fprintf(stdout, fmsg);

    if(level & g_StderrLogLevel)
      fprintf(stderr, fmsg);
  }

  return retval;
}
